package com.pb.metadata.controller;

import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.entity.excel.Column;
import com.pb.infra.oth.entity.excel.Excel;
import com.pb.infra.oth.entity.excel.ExcelSheet;
import com.pb.infra.oth.util.*;
import com.pb.metadata.entity.ImportDimData;
import com.pb.metadata.service.DimManagementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 维度管理
 * @author weiziyu
 * @date 2023.02.07
 */

@Slf4j
@RestController
@RequestMapping("v1/metadata/dimManagement")
//@RequestMapping("v1/metadata/dimManagement")
public class DimManagementController {
    /**
     * 业务逻辑对象
     */
    @Resource
    private DimManagementService dimManagementService;

    /**
     * 日志操作表
     */
    private static final String TABLE_NAME = "param_code_type";

    /**
     * 日志操作功能名
     */
    private static final String OPERATION_MENU = "维度树管理";

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private Class DimData;


    /**
     * 查询维度数据
     * @return
     */
    @GetMapping("selectDimData")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result selectDimData(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        return dimManagementService.selectDimData(map);
    }

    /**
     * 查询统一管理维度数据
     * @return
     */
    @GetMapping("selectComDimData")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result selectComDimData(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        return dimManagementService.selectComDimData(map);
    }

    /**
     * 查询param_code_type最大CODE_TYPE_ID
     *
     */
    @GetMapping("selMaxCodeTypeId")
    public Long selMaxCodeTypeId(@RequestParam Map<String, Object> map) {
        return dimManagementService.selMaxCodeTypeId(map);
    }

    /**
     * 保存维度数据
     * @return
     */
    @PostMapping("saveDimDate")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result saveDimDate(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        //获取请求体内的token
        String token = request.getHeader(jwtTokenConfig.getHeader());
        //通过token在redis中获取用户信息
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        map.put("createUser",userInfo.getUserId());
        map.put("updateUser",userInfo.getUserId());
        map.put("positionId",userInfo.getPositionId());
        dimManagementService.saveDimDate(map);
        return Result.OK_EMPTY;
    }

    /**
     * 修改维度数据
     * @return
     */
    @PostMapping("updateDimDate")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result updateDimDate(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        //获取请求体内的token
        String token = request.getHeader(jwtTokenConfig.getHeader());
        //通过token在redis中获取用户信息
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        map.put("updateUser",userInfo.getUserId());
        dimManagementService.updateDimDate(map);
        return Result.OK_EMPTY;
    }

    /**
     * 删除维度数据
     * @return
     */
    @PostMapping("delDimDate")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result delDimDate(@RequestBody Map<String, Object> map) {
        dimManagementService.delDimDate(map);
        return Result.OK_EMPTY;
    }

    /**
     * 查询维度树
     * @return
     */
    @GetMapping("selectTree")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result selectTree(@RequestParam Map<String, Object> map) {
        return dimManagementService.selectTree(map);
    }

    //新增树节点
    @PostMapping("insertNode")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result insertNode(@RequestBody Map<String, Object> paramMap, HttpServletRequest request) {
        //获取请求体内的token
//        String token = request.getHeader(jwtTokenConfig.getHeader());
        //通过token在redis中获取用户信息
//        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
//        paramMap.put("corpId",userInfo.getCorpId());
//        System.out.println(paramMap);
        return dimManagementService.insertNode(paramMap);
    }

    //查询节点编码是否唯一
    @PostMapping("validUnique")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result validUnique(@RequestBody Map<String, Object> paramMap) {
        return dimManagementService.validUnique(paramMap);
    }

    //删除树节点
    @PostMapping("deleteNode")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result deleteNode(@RequestBody Map<String, Object> paramMap) {
        return dimManagementService.deleteNode(paramMap);
    }

    //修改树节点
    @PostMapping("updateNode")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result updateNode(@RequestBody Map<String, Object> paramMap) {
        return dimManagementService.updateNode(paramMap);
    }

    @PostMapping("exportTree")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public void exportIndexSubqueryExcel(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        ExcelSheet sheet = new ExcelSheet();
        sheet.setHeader(new String[][]{{ "树编码", "树描述", "节点编码", "节点名称", "父节点", "叶子标识"}});
        sheet.setColumn(new Column[]{new Column("businessCodeType"), new Column("cnName"), new Column("businessCode"), new Column("nodeName"), new Column("parentId"), new Column("leafFlag")});
        List<Map<String, Object>> map1 = dimManagementService.selTreeData(map);
        sheet.setData(map1);
        ExportExcelUtil.exportExcel2007(new Excel("树管理"), new ExcelSheet[]{sheet}, response);
    }

    //更改树节点层级关系(拖拽)
    @PostMapping("updateNodeHierarchy")
    @SysLog(tableName = "param_code_dim", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result updateNodeHierarchy(@RequestBody Map<String, Object> paramMap) {
        return dimManagementService.updateNodeHierarchy(paramMap);
    }

    /**
     * 查询关联码值列表
     * @return
     */
    @GetMapping("getrelaStdCodeList")
    @SysLog(tableName = "PARAM_CODE_TYPE", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result getrelaStdCodeList(@RequestParam Map<String, Object> map) {
        return dimManagementService.getrelaStdCodeList(map);
    }

    /**
     * 查询维度类型列表
     * @return
     */
    @GetMapping("selDimTypeList")
    @SysLog(tableName = "PARAM_DIM_TYPE", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result selDimTypeList(@RequestParam Map<String, Object> map) {
        return dimManagementService.selDimTypeList(map);
    }

    /**
     * 属性注册
     * @return
     */
    @PostMapping("dimAttrTableData")
    @SysLog(tableName = "param_dim_attr_value", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result dimAttrTableData(@RequestBody Map<String, Object> paramMap) {
        return dimManagementService.dimAttrTableData(paramMap);
    }

    /**
     * 查询关联码值对应标准编码
     * @return
     */
    @PostMapping("getmateCodeValueList")
    @SysLog(tableName = "param_code_type", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result getmateCodeValueList(@RequestBody Map<String, Object> paramMap) {
        return dimManagementService.getmateCodeValueList(paramMap);
    }

    /**
     * 保存维度类型值
     * @return
     */
    @PostMapping("savedimAttrTableData")
    @SysLog(tableName = "param_dim_attr_vlaue", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result saveDimAttrTableData(@RequestBody List<Map<String, Object>> paramMap) {
        return Result.ok(dimManagementService.saveDimAttrTableData(paramMap));
    }

    /**
     * 查询维度树编码是否唯一
     * @return
     */
    @PostMapping("validUniqueBusinessCodeType")
    @SysLog(tableName = "PARAM_DIM_TYPE", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result validUniqueBusinessCodeType(@RequestBody Map<String, Object> map) {
        return dimManagementService.validUniqueBusinessCodeType(map);
    }

    //导入树节点数据
    @PostMapping("importExcel")
    public Result importExcel(@RequestParam Map<String, Object> paramMap, HttpServletRequest request,MultipartHttpServletRequest multRequest) throws IOException {
        Map<String, Object> responseMap = new HashMap<>();
        InputStream input = null;
        //获取请求体内的token
        String token = request.getHeader(jwtTokenConfig.getHeader());
        //通过token在redis中获取用户信息
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        try{
            MultipartFile excelFile = multRequest.getFile("excel-file");
            input = excelFile.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(input);
            //组装List集合
            Object checkMap = dimManagementService.checkExcelData(paramMap, workbook, 1, 1);
            if (checkMap instanceof String) {
                //检查未通过
                responseMap.put("code", -1);
                responseMap.put("msg", checkMap.toString());
            } else {
                //检查通过
                List<ImportDimData> checkList = (List<ImportDimData>) checkMap;
                System.out.println(checkList);
                //全量删除树节点
                System.out.println(paramMap);
                dimManagementService.delAllTreeNode(paramMap);
                //全量插入
                dimManagementService.insertExcelData(checkList);
                responseMap.put("msg", "导入成功，共导入：" + checkList.size() + "条数据");
            }
        }catch (Exception e) {
            e.printStackTrace();
            responseMap.put("code", -1);
            responseMap.put("msg", "导入失败");
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                responseMap.put("code", -1);
                responseMap.put("msg", "导入失败");
                log.error("关闭文件流失败", e);
            }
        }


        return Result.ok(responseMap.get("msg"));
    }

    /**
     * 查询维度树已有属性
     * @return
     */
    @PostMapping("selDefaultCheckedTreeNodeList")
    @SysLog(tableName = "PARAM_DIM_ATTR_VALUE", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result selDefaultCheckedTreeNodeList(@RequestBody Map<String, Object> map) {
        return dimManagementService.selDefaultCheckedTreeNodeList(map);
    }

    /**
     * 保存维度树多属性值
     * @return
     */
    @PostMapping("saveNodesAttrValues")
    @SysLog(tableName = "PARAM_DIM_ATTR_VALUE", action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result saveNodesAttrValues(@RequestBody List<Map<String, Object>> list) {
        return Result.ok(dimManagementService.saveNodesAttrValues(list));
    }

}
